package com.github.binarywang.demo.wx.mp.utils;


import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Utils {
    public static void main(String[] args){
        getToken();
    }

    public static final String TOKEN="mayikt";    //TOKEN就是自己填写的
    public static final String APPID="wx83c7277bbc6d7a9e";
    public static final String APPSECRET="e7601539a62a2abfcaf4457e05d9621e";

    //用于存储access_token
   // private static AccessToken at;

    /*
     * 获取accessToken，有效期2小时
     * */
    private static void getToken() {

        String url = " https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "&appid=" + APPID + "&secret=" + APPSECRET;
            URL realUrl = new URL(urlNameString);

            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();

            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("Accept-Charset", "utf-8");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();

            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();

            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                connection.getInputStream(),"utf-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }

        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }

        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }


        Gson gson = new Gson();
        HashMap hashMap = gson.fromJson(result, HashMap.class);
        String access_token = (String) hashMap.get("access_token");
        Double expires_in = (Double) hashMap.get("expires_in");
        //创建access_token，并存起来
        //at = new AccessToken(access_token, expires_in);
        System.out.println("access_token:"+access_token);
        System.out.println("expires_in:"+expires_in);
    }

    /*
     * 获取access_token的方法    直接HttpRequest.getAccessToken()即可返回access_token值
     * */
    /*public static String getAccessToken() {
        if (at == null || at.isExpired()) {
            //过期则创建新的access_token
            getToken();
        }
        //返回access_token
        return at.getAccess_token();
    }*/

    /*
     * 验证签名
     * */
    public static boolean check(String timestamp, String nonce, String signature) {

        //1、将token、timestamp、nonce进行字典排序
        String[] strs = new String[]{TOKEN, timestamp, nonce};
        Arrays.sort(strs);

        //2、将三个参数字符串拼接成一个字符串进行sha1加密
        String str = strs[0] + strs[1] + strs[2];
        String mysignature = sha1(str);

        //返回对比结果
        return mysignature.equalsIgnoreCase(signature);
    }

    /*
     * 加密方法
     * */
    private static String sha1(String src) {

        try {
            //获取一个加密对象
            MessageDigest md = MessageDigest.getInstance("sha1");
            //加密
            byte[] digest = md.digest(src.getBytes());
            char[] chars = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
            StringBuffer sb = new StringBuffer();
            //处理结果集
            for (byte b : digest) {
                sb.append(chars[(b >> 4) & 15]);
                sb.append(chars[b & 15]);
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }
}
